package ar.com.ford.it.fullEconomics.view.form;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.apache.struts.validator.ValidatorForm;
import ar.com.ford.it.fullEconomics.persistence.dto.Teesm02Currvalue;
import ar.com.ford.it.fullEconomics.util.FullEconomicsDateUtil;

public class CurrencyValuesForm extends ValidatorForm {

    private final double maxConvertRate = 99999999.99999;

    private String section;
    private String fechaFind;
    private String currencyOrigFind;
    private String currencyDestFind;
    private String convertRate;
    private String fechaIn;
    private String fechaOut;
    private String editBlocked;
    private Collection currencyValues;
    private String currencyOrig;
    private String currencyDest;
    private Teesm02Currvalue currencyValueSelected;
    String confirmMovePrevDate;
    String showConfirmMoveDate;

    /**
     * Resetea el formulario
     * 
     */
    public void resetForm() {
        this.section = "";
        this.editBlocked = "false";
        this.fechaFind = null;
        this.currencyOrigFind = "-1";
        this.currencyDestFind = "-1";
        this.currencyDest = null;
        this.currencyOrig = null;
        this.currencyValues = null;
        this.currencyValueSelected = null;
        this.fechaIn = null;
        this.fechaOut = null;
        this.convertRate = null;
        this.confirmMovePrevDate = "false";
        this.showConfirmMoveDate = "false";
    }

    /**
     * Limpia los campos utilizados en el form para la creacion o actualizacion
     * de Currencys
     * 
     */
    public void clearCreateUpdateFields() {
        this.fechaIn = null;
        this.fechaOut = null;
        this.convertRate = null;
        this.currencyOrig = null;
        this.currencyDest = null;
        this.editBlocked = "false";
    }

    public void clearFindFields() {
        this.fechaFind = null;
        this.currencyOrigFind = "-1";
        this.currencyDestFind = "-1";
        this.editBlocked = "false";
    }

    public Collection getCurrencyValues() {
        return currencyValues;
    }

    public void setCurrencyValues(Collection currencyValues) {
        this.currencyValues = currencyValues;
    }

    /**
     * Setea el Currency seleccionado para luego ser modificado
     * 
     * @param key
     * @param value
     */
    public void setEditMapped(String key, String value) {
        List currencyValues = (List) this.getCurrencyValues();
        if (currencyValues != null)
            this.setCurrencyValueSelected((Teesm02Currvalue) currencyValues
                    .get(Integer.parseInt(key) - 1));
    }

    /**
     * Setea el Currency seleccionada para luego ser eliminado
     * 
     * @param key
     * @param value
     */
    public void setDeleteMapped(String key, String value) {
        setEditMapped(key, value);
    }

    public Teesm02Currvalue getCurrencyValueSelected() {
        return currencyValueSelected;
    }

    public void setCurrencyValueSelected(Teesm02Currvalue currencyValueSelected) {
        this.currencyValueSelected = currencyValueSelected;
    }

    /**
     * Setea los campos del cuadro de creacion/modificacion de Currencys
     * 
     * @param currency
     */
    public void setCurrencyForEdit(Teesm02Currvalue currencyValue) {

        Calendar calFechaOut = Calendar.getInstance();
        calFechaOut.setTime(currencyValue.getEesm02CurrencyValOutDateY());

        Calendar calFechaIn = Calendar.getInstance();
        calFechaIn.setTime(currencyValue.getEesm02CurrencyValueDateY());

        BigDecimal bgConvertRate = currencyValue.getEesm02ConvertRateAmountA();

        this.setFechaOut(FullEconomicsDateUtil.format(calFechaOut));
        this.setFechaIn(FullEconomicsDateUtil.format(calFechaIn));
        this.setConvertRate(bgConvertRate.toString());
        this.setCurrencyDest(currencyValue.getEesm02DestCurrencyCodeC()
                .getEesm01CurrencyCodeC());
        this.setCurrencyOrig(currencyValue.getEesm02OrigCurrencyCodeC()
                .getEesm01CurrencyCodeC());

    }

    /**
     * Setea los campos del Currency Value para su posterior creacion
     * 
     * @return Currency con los campos minimos seteados para la posterior
     * creacion
     */
    public Teesm02Currvalue getCurrencyValueForCreate() {
        Teesm02Currvalue currencyValue = new Teesm02Currvalue();

        return currencyValue;
    }

    /**
     * Setea los campos del Currency para su posterior actualizacion
     * 
     * @param currency
     * Currency a actualizar
     * @return Currency con los campos a actualizar modificados
     */
    public Teesm02Currvalue getCurrencyValueForUpdate(
                                                      Teesm02Currvalue currencyValue) {
        return currencyValue;
    }

    public String getSection() {
        return section;
    }

    public void setSection(String section) {
        this.section = section;
    }

    /**
     * Genera las validaciones necesarias.
     */
    public ActionErrors validate(ActionMapping mapping,
                                 HttpServletRequest request) {

        ActionErrors ae = new ActionErrors();
        MessageResources resources = (MessageResources) request
                .getAttribute(org.apache.struts.Globals.MESSAGES_KEY);

        if ("createUpdate".equalsIgnoreCase(this.getSection())) {

            try {

                // Verifico y formateo la fechas In
                if (StringUtils.isBlank(this.getFechaIn())) {
                    ae
                            .add(
                                    ActionMessages.GLOBAL_MESSAGE,
                                    new ActionMessage(
                                            "errors.required",
                                            resources
                                                    .getMessage("currencyValues.label.tableHeader.fechaIn")));
                } else {
                    if (FullEconomicsDateUtil.format(this.getFechaIn()) == null) {
                        ae
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "errors.date",
                                                resources
                                                        .getMessage("currencyValues.label.tableHeader.fechaIn")));
                    }
                }
            } catch (Exception e) {
                ae
                        .add(
                                ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        "errors.date",
                                        resources
                                                .getMessage("currencyValues.label.tableHeader.fechaIn")));
            }

            try {
                // Verifico y formateo la fechas Out
                if (!StringUtils.isBlank(this.getFechaOut())) {
                    if (FullEconomicsDateUtil.format(this.getFechaOut()) == null) {
                        ae
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "errors.date",
                                                resources
                                                        .getMessage("currencyValues.label.tableHeader.fechaOut")));
                    }
                }
            } catch (Exception e) {
                ae
                        .add(
                                ActionMessages.GLOBAL_MESSAGE,
                                new ActionMessage(
                                        "errors.date",
                                        resources
                                                .getMessage("currencyValues.label.tableHeader.fechaOut")));
            }

            // Si no hubo errores
            if (ae.size() == 0)
                if (!StringUtils.isBlank(this.getFechaOut())) {
                    // Verifico que la fecha de inicio sea menor a la fecha de
                    // fin
                    if (FullEconomicsDateUtil.getDifference(this.getFechaIn(),
                            this.getFechaOut()) <= 0) {
                        ae
                                .add(
                                        ActionMessages.GLOBAL_MESSAGE,
                                        new ActionMessage(
                                                "errors.date.range",
                                                resources
                                                        .getMessage("currencyValues.label.tableHeader.fechaOut"),
                                                resources
                                                        .getMessage("currencyValues.label.tableHeader.fechaIn")));
                    }
                }
            if (this.getCurrencyDest().equals("")) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "currencyValues.error.currencyDestRequired"));
            }
            if (this.getCurrencyOrig().equals("")) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "currencyValues.error.currencyOrigRequired"));
            } else {
                if (this.getCurrencyDest().equals(this.getCurrencyOrig())) {
                    ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "currencyValues.error.invalidConvertion"));
                }
            }
            try {
                if (Double.valueOf(this.getConvertRate()) > maxConvertRate)
                    ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                            "currencyValues.error.maxConvertRate",
                            maxConvertRate));
            } catch (Exception e) {
                ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
                        "currencyValues.error.invalidConvertRate"));
            }
        }

        return ae;
    }

    public String getFechaIn() {
        return fechaIn;
    }

    public void setFechaIn(String fechaIn) {
        this.fechaIn = fechaIn;
    }

    public String getFechaOut() {
        return fechaOut;
    }

    public void setFechaOut(String fechaOut) {
        this.fechaOut = fechaOut;
    }

    public String getEditBlocked() {
        return editBlocked;
    }

    public void setEditBlocked(String editBlocked) {
        this.editBlocked = editBlocked;
    }

    public String getFechaFind() {
        return fechaFind;
    }

    public void setFechaFind(String fechaInFind) {
        this.fechaFind = fechaInFind;
    }

    public String getCurrencyDest() {
        return currencyDest;
    }

    public void setCurrencyDest(String currencyDest) {
        this.currencyDest = currencyDest;
    }

    public String getCurrencyOrig() {
        return currencyOrig;
    }

    public void setCurrencyOrig(String currencyOrig) {
        this.currencyOrig = currencyOrig;
    }

    public String getCurrencyDestFind() {
        return currencyDestFind;
    }

    public void setCurrencyDestFind(String currencyDestFind) {
        this.currencyDestFind = currencyDestFind;
    }

    public String getCurrencyOrigFind() {
        return currencyOrigFind;
    }

    public void setCurrencyOrigFind(String currencyOrigFind) {
        this.currencyOrigFind = currencyOrigFind;
    }

    public String getConvertRate() {
        return convertRate;
    }

    public void setConvertRate(String convertRate) {
        this.convertRate = convertRate;
    }

    public String getConfirmMovePrevDate() {
        return confirmMovePrevDate;
    }

    public void setConfirmMovePrevDate(String confirmMovePrevDate) {
        this.confirmMovePrevDate = confirmMovePrevDate;
    }

    public String getShowConfirmMoveDate() {
        return showConfirmMoveDate;
    }

    public void setShowConfirmMoveDate(String showConfirmMoveDate) {
        this.showConfirmMoveDate = showConfirmMoveDate;
    }

}
